package cn.danger.com.presenter;

import android.content.Context;
import android.os.Handler;
import android.os.Message;

import cn.danger.com.model.action.ModifyPhoneModel;
import cn.danger.com.model.action.ModifyPhoneModelImpl;
import cn.danger.com.model.listener.OnCommonListener;
import cn.danger.com.util.Constants;
import cn.danger.com.util.FileCacheService;
import cn.danger.com.view.CommonView;

/**
 * Created by 俊 on 2016/12/30.
 */
public class ModifyPhonePresenterImpl implements ModifyPhonePresenter {

    private Context context;
    private CommonView view;
    private ModifyPhoneModel model;
    private Handler handler;
    private int time = 60;

    public ModifyPhonePresenterImpl(Context context, CommonView view, Handler handler) {
        this.context = context;
        this.view = view;
        model = new ModifyPhoneModelImpl(context);
        this.handler = handler;
    }

    @Override
    public void sendCheckCode(String phone) {
        view.showDialog();
        model.sendCheckCode(phone, new OnCommonListener() {
            @Override
            public void onSuccess(String message) {
                view.hideDialog();
                new MyThread().start();
                view.showMessage(Constants.SUCCESS_TO_SEND_CHECK_CODE);
            }

            @Override
            public void onError(String error) {
                view.hideDialog();
                view.showMessage(error);
            }
        });
    }

    @Override
    public void updatePhone(final String phone, String check_code) {
        view.showDialog();
        model.updatePhone(phone, check_code, new OnCommonListener() {
            @Override
            public void onSuccess(String message) {
                new FileCacheService(context).updatePhone(phone);
                view.hideDialog();
                view.showMessage(Constants.SUCCESS_TO_BIND_PHONE);
            }

            @Override
            public void onError(String error) {
                view.hideDialog();
                view.showMessage(error);
            }
        });
    }

    private class MyThread extends Thread {

        @Override
        public void run() {
            super.run();
            while (true) {
                if (time == 0) {
                    handler.sendEmptyMessage(2);
                    break;
                }
                --time;
                try {
                    sleep(1000);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                Message message = Message.obtain();
                message.what = 1;
                message.arg1 = time;
                handler.sendMessage(message);
            }
        }

    }
}
